﻿using Autodesk.AutoCAD.DatabaseServices;

namespace BasicTools
{
    /// <summary>
    /// 将实体添加到模型空间的工具类
    /// </summary>
    public static class AddEntityToModelSpaceTools
    {
        /// <summary>
        /// 将图形对象添加到图形文件中
        /// </summary>
        /// <param name="db">图形数据库</param>
        /// <param name="ent">图形对象</param>
        /// <returns>图形对象的ObjectId</returns>
        public static ObjectId AddEntityToModeSpace(this Database db, Entity ent)
        {
            ObjectId entId = ObjectId.Null;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                entId = btr.AppendEntity(ent);
                trans.AddNewlyCreatedDBObject(ent, true);
                trans.Commit();
            }
            return entId;
        }

        /// <summary>
        /// 添加多个图形对象到图形文件中
        /// </summary>
        /// <param name="db">图形数据库</param>
        /// <param name="ents">图形对象</param>
        /// <returns>图形对象的ObjectId数组</returns>
        public static ObjectId[] AddEntityToModeSpace(this Database db, params Entity[] ents)
        {
            ObjectId[] entIds = new ObjectId[ents.Length];
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                for (int i = 0; i < ents.Length; i++)
                {
                    entIds[i] = btr.AppendEntity(ents[i]);
                    trans.AddNewlyCreatedDBObject(ents[i], true);
                }
                trans.Commit();
            }
            return entIds;
        }
    }
}
